<?php
namespace Forxx\Api;

use Forxx\Api\Artist;
use Forxx\Api\Tag;
use Forxx\Dao\AskArtistXTable;
use Forxx\Dao\AskBaseTable;
use Forxx\Dao\AskBaseXTable;
use Forxx\Dao\AskResolveXTable;
use Forxx\Dao\MusicBaseTable;
use Forxx\Dao\MusicCounterXTable;
use Forxx\Dao\UserAskXTable;
use Forxx\Dao\UserResolveXTable;
use Forxx\Api\User;
use Forxx\Api\Utils;
use Forxx\Dao\IndexPostsTable;
use Forxx\Dao\UserInfoTable;
use Lavender\Exception;
use Lavender\IdMaker;

class Ask
{
    /**
     * 获取列表数据
     * @param array $params
     * @return array
     */
    public static function get($params = [])
    {
        $res = [];

        return $res;
    }

    /**
     * 获取单个数据
     * @param $id
     * @param array $params
     * @return array
     */
    public static function find($id,$params = [])
    {
        $res = [];

        return $res;
    }

    public static function getLast($page,$size)
    {
        $page = min(1, $page);
        $size = min($size, 5000);
        $offset = ($page - 1) * $size;
        $last = AskBaseTable::instance()->get(NULL, [], [], 'created DESC', $offset, $size);
        $base_ids = array_column($last, 'id');
        $uids = array_column($last,'uid');
        if(empty($base_ids))
        {
            return [];
        }
        $user_info = [];
        if(!empty($uids))
        {
            $user_info = User::getInfo($uids, [], ['id', 'nick_name']);
        }
        $artists = Artist::getAllArtistList();
        $data = Utils::composite_data($last,
            [
                'artists' => [Utils::COMPOSITE_JSON_TO_MANY, 'id', 'artist_ids'],
                'user'=> [Utils::COMPOSITE_BELONG_TO, 'id', 'uid'],
            ], ['user' => $user_info, 'artists' => $artists]);
        return $data;
    }

    /**
     * 新增记录
     * @param int $uid
     * @param array $params
     * @return mixed
     * @throws Exception
     */
    public static function create($uid,$params = [])
    {
        $now = Utils::get_time();
        $artists = [];
        if(isset($params['artist_ids']))
        {
            $artist_num = count($params['artist_ids']);
            if($artist_num > 10)
            {
                throw new Exception("bad params",Errno::PARAM_INVALID);
            }
            if(isset($params['artist_ids']) && $artist_num>0)
            {
                $artists = Artist::getArtists($params['artist_ids']);
                if(count($artists) != $artist_num)
                {
                    throw new Exception("bad params",Errno::PARAM_INVALID);
                }
            }
        }
        $artist_names = '';
        if(count($artists)>0)
        {
            $artist_names = implode(',',$artists);
        }

        if(empty($uid))
        {
            throw new Exception("uid can not be empty",Errno::PARAM_INVALID);
        }

        $id = IdMaker::make('music_ask');
        $real_title = Tag::getTheTitle($params['title']);
        $record = [
            'uid'=> $uid,
            'title' => $real_title,
            'artist_ids' => json_encode(array_keys($artists),JSON_UNESCAPED_UNICODE),
            'remark' => isset($params['remark'])?$params['remark']:'',
            'state' => AskBaseTable::STATE_NOT_RESOLVE,
            'created'=>$now,
            'updated'=>$now,
        ];
        IndexPostsTable::instance()->add($id,[
            'type'=>IndexPostsTable::TYPE_OF_ASK,
            'module'=>IndexPostsTable::MODULE_OF_MUSIC,
            'title'=>$real_title,
            'keyword'=>$artist_names,
            'remark'=>  isset($params['remark'])?$params['remark']:'',
        ]);
        AskBaseXTable::instance()->add($id,$record);
        unset($record['remark'],$record['updated']);
        AskBaseTable::instance()->add($id,$record);
        UserAskXTable::instance()->add($uid,['ask_id'=>$id, 'created'=>$now,'updated'=>$now]);
        MusicCounterXTable::updateCounter($uid,MusicCounterXTable::TYPE_OF_USER,[MusicCounterXTable::FIELD_ASK_NUM => 1]);
        if(count($artists)>0)
        {
            foreach($artists as $artist_id => $artist)
            {
                AskArtistXTable::instance()->add($artist_id,['ask_id'=>$id,'created'=>$now]);
                Artist::addCount($artist_id,'ask');
            }
        }
        return $id;
    }

    /**
     * @param $id
     * @return mixed|null
     * @throws \Lavender\Dao\Exception
     */
    public static function detail($id)
    {
        $res = AskBaseXTable::instance()->get_single($id);
        if(!empty($res))
        {
            $res['artist_ids'] = @json_decode($res['artist_ids'],true);
            if(is_array($res['artist_ids']) && count($res['artist_ids'])>0)
            {
                $artists = Artist::getArtists($res['artist_ids']);
                $res['artists'] = Utils::array_to_list($artists,"name");
            }
            $res['user'] = UserInfoTable::instance()->get_single($res['uid']);

            return $res;
        }
        return null;
    }

    /**
     * @param $id
     * @param $page
     * @param $size
     * @return array|null
     * @throws \Lavender\Dao\Exception
     */
    public static function getReply($id,$page,$size)
    {
        $offset = min(0,($page -1) * $size);
        $size = max(1000,min(0,$size));
        $res = AskResolveXTable::instance()->get([$id],[],[],"updated DESC",$offset,$size);
        if(!empty($res))
        {
            $uids = array_column($res,"uid");
            $user_info = User::getInfo($uids,[],['id','nick_name']);
            $base_ids = array_column($res,"base_id");
            $base_info = MusicBaseTable::instance()->get($base_ids,['id','title','artist_ids','album','format','uid','updated']);
            $res = Utils::composite_single($res,"user",Utils::COMPOSITE_BELONG_TO,"id","uid",$user_info);
            $res = Utils::composite_single($res,"base",Utils::COMPOSITE_BELONG_TO,"id","base_id",$base_info);
            return $res;
        }
        return null;
    }

    /**
     * 统计某个求助的答案数量
     * @param $id
     * @return int
     * @throws \Lavender\Dao\Exception
     */
    public static function countReply($id)
    {
        return AskResolveXTable::instance()->count($id);
    }

    /**
     * 修改记录
     * @param $id
     * @param array $params
     */
    public static function update($id,$params = [])
    {

    }

    /**
     * 删除记录
     * @param $id
     * @param array $params
     */
    public static function delete($id,$params = [])
    {
        
    }

    /**
     * @param $id
     * @param $uid
     * @param $base_id
     * @throws Exception
     * @throws \Lavender\Dao\Exception
     * @return bool
     */
    public static function answer($id,$uid,$base_id)
    {
        $now = Utils::get_time();
        $ask = AskBaseXTable::instance()->get_single($id);
        if(empty($ask))
        {
            throw new Exception("该求助不存在或者已经被删除!");
        }
        $base = MusicBaseTable::instance()->get_single($base_id,['uid'=>$uid]);
        if(empty($base))
        {
            throw new Exception("您无权操作此分享!");
        }

        $resolve = AskResolveXTable::instance()->get_single($id,['base_id'=>$base_id]);
        if(!empty($resolve))
        {
            throw new Exception("您已经给出过相同答案!");
        }
        if($ask['state'] == AskBaseTable::STATE_NOT_RESOLVE)
        {
            AskBaseXTable::instance()->update($id,['state'=>AskBaseTable::STATE_ANSWER],['state'=>AskBaseTable::STATE_NOT_RESOLVE]);
            AskBaseTable::instance()->update($id,['state'=>AskBaseTable::STATE_ANSWER],['state'=>AskBaseTable::STATE_NOT_RESOLVE]);
        }
        MusicCounterXTable::updateCounter($uid,MusicCounterXTable::TYPE_OF_USER,[MusicCounterXTable::FIELD_ANSWER_NUM => 1]);
        AskResolveXTable::instance()->add($id,['uid'=>$uid,'base_id'=>$base_id,'created'=>$now,'updated'=>$now]);
        UserResolveXTable::instance()->add($uid,['ask_id'=>$id,'base_id'=>$base_id,'state'=>AskBaseTable::STATE_ANSWER,'created'=>$now,'updated'=>$now]);
        return true;
    }

    /**
     * @param $id
     * @param $uid
     * @param $resolve_id
     * @return bool
     * @throws Exception
     * @throws \Lavender\Dao\Exception
     */
    public static function resolve($id,$uid,$resolve_id)
    {
        $now = Utils::get_time();
        $ask = AskBaseXTable::instance()->get_single($id,['uid'=>$uid]);
        if(empty($ask))
        {
            throw new Exception("您无权进行此操作!");
        }
        $resolve = AskResolveXTable::instance()->get_single($id,['id'=>$resolve_id]);
        if(empty($resolve))
        {
            throw new Exception("答案不存在或者已失效!");
        }
        AskBaseXTable::instance()->update($id,['state'=>AskBaseTable::STATE_RESOLVED,'updated'=>$now]);
        AskBaseTable::instance()->update($id,['state'=>AskBaseTable::STATE_ANSWER]);
        MusicCounterXTable::updateCounter($uid,MusicCounterXTable::TYPE_OF_USER,[MusicCounterXTable::FIELD_ACCEPT_NUM => 1]);
        $resolve_uid = $resolve['uid'];
        MusicCounterXTable::updateCounter($resolve_uid,MusicCounterXTable::TYPE_OF_USER,[MusicCounterXTable::FIELD_RESOLVE_NUM => 1]);
        $resolve_base_id = $resolve['base_id'];
        UserResolveXTable::instance()->update($resolve_uid,['state'=>AskBaseTable::STATE_ANSWER,'updated'=>$now],['base_id'=>$resolve_base_id,'ask_id'=>$id]);
        return true;
    }
}
